package com.hmkj.crm.billing.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmkj.crm.billing.domain.company.DeliveryCompaniesInfo;
import com.hmkj.crm.billing.domain.order.SalesOrder;
import com.hmkj.crm.billing.domain.product.ProductInfo;
import com.hmkj.crm.billing.dto.SalesOrderDTO;
import com.hmkj.crm.billing.mapper.order.SalesOrderMapper;
import com.hmkj.crm.billing.service.company.DeliveryCompaniesInfoService;
import com.hmkj.crm.billing.service.order.SalesOrderService;
import com.hmkj.crm.billing.service.product.ProductInfoService;
import com.hmkj.crm.billing.service.relevance.RelProductInventoryService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 销售订单(出库)服务Impl
 *
 * @author sks.lwei
 * @date 2020/01/16
 */
@Log4j2
@Service
public class SalesOrderServiceImpl extends ServiceImpl<SalesOrderMapper, SalesOrder> implements SalesOrderService {

    /**
     * rel产品库存服务
     */
    @Resource
    private RelProductInventoryService productInventoryService;

    /**
     * 产品信息服务
     */
    @Resource
    private ProductInfoService productInfoService;

    /**
     * 配送公司信息服务
     */
    @Resource
    private DeliveryCompaniesInfoService deliveryCompaniesInfoService;

    @Override
    public IPage<SalesOrderDTO> listSalesOrderPage(Page<SalesOrder> page, Wrapper<SalesOrder> wrapper) {
        Page<SalesOrder> orderPage = this.page(page, wrapper);
        return orderPage.convert(salesOrder -> {
            SalesOrderDTO dto = new SalesOrderDTO(salesOrder);
            ProductInfo productInfo = productInfoService.getProductInfoByUuid(salesOrder.getProductUuid());
            DeliveryCompaniesInfo deliveryCompaniesInfo = deliveryCompaniesInfoService.getDeliveryCompaniesInfoByuuid(salesOrder.getDeliveryUuid());
            return dto.toSalesOrderDTO(productInfo, deliveryCompaniesInfo);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void sales(String deliveryUuid, SalesOrder salesOrder) {
        log.info("销售订单, 订单uuid[{}]", salesOrder.getUuid());

        salesOrder.setUuid("S"+ IdWorker.getMillisecond());
        this.save(salesOrder);

        //削减库存
        productInventoryService.down(deliveryUuid, salesOrder);
        log.info("订单出库完成");
    }

    @Override
    public SalesOrder getSalesOrderByUuid(String uuid) {
        QueryWrapper<SalesOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("uuid", uuid);
        return this.getOne(wrapper);
    }
}
